﻿<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="lib/jsoneditor/css/jsoneditor.css" rel="stylesheet" type="text/css" />
    <script src="lib/jsoneditor/js/jsoneditor.js"></script>
    <style type="text/css">
        .container {
            display: flex;
        }
        #editor {
            background: #bbbbbb;
            flex: 1; /* 1 代表盡可能最大，會自動填滿除了 header footer 以外的空間 */
        }
        .jsoneditor {
            height: calc(100vh - 60px);
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="editor"></div>
    </div>
    <script>
        var json_data = {};
        const container = document.getElementById("editor");
        const options = {
            mode: 'code',
            ace: ace,
            modes: ['text', 'code', 'tree', 'form', 'view', 'preview'],
            onChangeText: function (jsonString) {
                if (jsonString == "" || jsonString == null) {
                    json_data = {};
                    console.log("onChangeText",json_data);
                }
            },
            onValidate: function (json) {
                json_data = JSON.stringify(json);
            }
        };
        const editor = new JSONEditor(container, options);
        editor.set(json_data);

        //监听message事件，C#的PostWebMessageAsString或PostWebMessageAsJson可以触发该事件
        window.chrome.webview.addEventListener('message', event => {
            var result = event.data;
            if (result.action == "set") {
                json_data = result.data;
                
                if (json_data.length == 0) {
                    json_data = {};
                } else {                    
                    editor.set(json_data);
                }
            }
            if (result.action == "get") {
                if (Object.keys(json_data).length === 0) {
                    //判断为空对象
                    json_data = JSON.stringify({}, null, 2);
                } else {
                    json_data = JSON.stringify(editor.get(), null, 2);
                }
                window.chrome.webview.postMessage(json_data);
            }
        });
    </script>
</body>
</html >
